<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="报表资源" prop="menuId" v-if="false">
        <el-tree-select 
            v-model="queryParams.menuId"
            :data="menuOptions" 
            node-key="id"
            :render-after-expand="false" 
            :disable-branch-nodes="true" 
            style="width: 300px" 
          />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in boc_auth_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="false">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['boc:authInfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5" v-if="false">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['boc:authInfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5" v-if="false">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['boc:authInfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5" v-if="false">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['boc:authInfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="authInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" v-if="false"/>
      <el-table-column label="报表名称" align="center" prop="menuName" />
      <el-table-column label="申请人" align="center" prop="applyName" />
      <el-table-column label="数据使用到期日" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请备注" align="center" prop="remark" />
      <el-table-column label="复核人" align="center" prop="checkName" />
      <el-table-column label="复核时间" align="center" prop="checkTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.checkTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="复核备注" align="center" prop="checkRemark" v-if="false"/>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="boc_auth_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template #default="scope">
          <el-button  type="success"  @click="handleUpdate(scope.row)" v-hasPermi="['boc:authInfo:check']" v-if="scope.row.status === '1' ? true : false">通过</el-button>
          <el-button  type="danger"  @click="handleNoPass(scope.row)" v-hasPermi="['boc:authInfo:check']" v-if="scope.row.status === '1' ? true : false">不通过</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改授权信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="authInfoRef" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="申请人" prop="createBy">
          <el-input v-model="form.createBy" type="text" disabled/>
        </el-form-item>
        <el-form-item label="申请报表" prop="">
          <el-input v-model="form.menuName" type="text" disabled/>
        </el-form-item>
        <el-form-item label="数据使用到期日" prop="endTime">
          <el-date-picker clearable
            v-model="form.endTime"
            :disabled-date="pickerOptions"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择结束时间"
            disabled>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="复核人" prop="checkId" v-if="false">
            <el-select v-model="form.checkId" placeholder="复核人" clearable style="width: 400px" disabled>
               <el-option
               v-for="item in checkUsersList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
               />
            </el-select>
         </el-form-item>       
        <el-form-item label="申请原因" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入申请原因" disabled/>
        </el-form-item>
        <el-form-item label="选择授权人" prop="empowerId">
            <el-select v-model="form.empowerId" placeholder="请选择授权人" clearable style="width: 400px">
               <el-option
               v-for="item in approveUsersList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
               />
            </el-select>
         </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handlePass">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AuthInfo">
import { listAuthInfoCheck, getAuthInfo, delAuthInfo, addAuthInfo, updateAuthInfo, checkAuthInfo } from "@/api/boc/authInfo";
import { getAuthMenu, getCheckUsers, getEmpowerUsers } from "@/api/boc/common";

const { proxy } = getCurrentInstance();
const { boc_auth_status } = proxy.useDict('boc_auth_status');

const authInfoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const menuOptions = ref([]);
const checkUsersList = ref([]);
const approveUsersList = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    menuId: null,
    applyId: null,
    checkId: null,
    checkTime: null,
    empowerId: null,
    empowerTime: null,
    checkRemark: null,
    empowerRemark: null,
    startTime: null,
    endTime: null,
    status: null,
  },
  rules: {
    menuId: [
      { required: true, message: "菜单ID不能为空", trigger: "blur" }
    ],
    endTime: [
      { required: true, message: "数据使用到期日", trigger: "blur" }
    ],
    applyId: [
      { required: true, message: "申请人不能为空", trigger: "blur" }
    ],
    checkId: [
      { required: true, message: "复核人不能为空", trigger: "blur" }
    ],
    empowerId: [
      { required: true, message: "授权人不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询授权信息列表 */
function getList() {
  loading.value = true;
  listAuthInfoCheck(queryParams.value).then(response => {
    authInfoList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
  getMenuTreeselect();
  //getCheckUsersList();
  getEmpowerUsersList();
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    authId: null,
    menuId: null,
    applyId: null,
    checkId: null,
    checkTime: null,
    empowerId: null,
    empowerTime: null,
    checkRemark: null,
    empowerRemark: null,
    startTime: null,
    endTime: null,
    status: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    menuName: null,
    applyName: null
  };
  proxy.resetForm("authInfoRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.authId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加复核信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _authId = row.authId || ids.value
  getAuthInfo(_authId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "复核操作";
  });
}

/** 复核通过 */
function handlePass(row) {
  proxy.$refs["authInfoRef"].validate(valid => {
    if (valid) {
      if (form.value.authId != null) {
        form.value.status = '2';
        checkAuthInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("复核通过");
          open.value = false;
          getList();
        });
      }
    }
  });
}


/** 复核不通过 */
function handleNoPass(row) {
  proxy.$modal.confirm('请确定是否"不通过"' +row.applyName +"申请<<"+row.menuName + '">>的数据下载申请？').then(function() {
    let jsonStr = `{"authId": ${row.authId},"status": 4}`;
    let data = JSON.parse(jsonStr);
    return checkAuthInfo(data);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("复核不通过");
  }).catch(() => {});
}


/** 提交按钮 */
function submitForm() {
  proxy.$refs["authInfoRef"].validate(valid => {
    if (valid) {
      if (form.value.authId != null) {
        updateAuthInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addAuthInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _authIds = row.authId || ids.value;
  proxy.$modal.confirm('是否确认删除授权信息编号为"' + _authIds + '"的数据项？').then(function() {
    return delAuthInfo(_authIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('boc/authInfo/export', {
    ...queryParams.value
  }, `authInfo_${new Date().getTime()}.xlsx`)
}

function getMenuTreeselect() {
  getAuthMenu().then(response => {
    menuOptions.value = response.data;
  });
}


function getCheckUsersList() {
  getCheckUsers().then(response => {
    checkUsersList.value = response.data;
  });
}

function getEmpowerUsersList() {
  getEmpowerUsers().then(response => {
    approveUsersList.value = response.data;
  });
}

function pickerOptions(time){
// date 入参是 Date()的实例
  let now = Date.now()
  let limitDays = 30 * 24 * 60 * 60 * 1000 // 30天的毫秒数
  let ts = time.getTime()
  // 只允许选择: 未来的30天
  if (ts >= now && ts <= now + limitDays) return false // 启用
  return true // 禁用
}

getList();
</script>
